import axios from "axios";
import {
  Message
} from 'element-ui';
import router from '../router'
import {
  getCookie
} from "./cookie";
import {
  Notification
} from 'element-ui';
axios.defaults.withCredentials = true

// 请求拦截器(头部携带token)
axios.interceptors.request.use(config => {
  let token = getCookie("token");
  config.headers['token'] = token;
  return config
}, error => {
  console.log(error);
})

//请求token的后置拦截（对token过期，错误等统一处理）
axios.interceptors.response.use(response => {
  let res = response.data;
  //请求正确
    //token过期
    if (res.code == "any") {
      Notification({
        title: res.message,
        type: "warning",
      });
      router.replace("/login")
    }
    //token错误
    if (res.code == "any") {
      Notification({
        title: res.message,
        type: "warning",
      });
      router.replace("/login")
    }
    //除了token错误，其他都正常返回
    else{
        return response
    }

}, )

let base = 'http://175.178.9.184:8848';
// let base = 'http://localhost:8848';
//传递json的post请求
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    headers: {
      'Authorization': getCookie("JSSESSIONID"),
    },
    url: `${base}${url}`,
    data: params,
    xhrFields: {
      withCredentials: true // 这里设置了withCredentials
    }

  })
}
//传递json的put请求
export const putRequest = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params,
    xhrFields: {
      withCredentials: true // 这里设置了withCredentials
    }

  })
}
//传递json的get请求
export const getRequest = (url, params) => {
  return axios({
    method: 'get',
    headers: {
      'Authorization': getCookie("JSSESSIONID"),
    },
    url: `${base}${url}`,
    data: params,
    xhrFields: {
      withCredentials: true // 这里设置了withCredentials
    }

  })
}
//传递json的delete请求
export const deleteRequest = (url, params) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`,
    data: params,
    xhrFields: {
      withCredentials: true // 这里设置了withCredentials
    }

  })
}
